from django.http import JsonResponse
from django.test import TestCase

# coding=UTF-8
import os
import cv2
from PIL import Image

from ad_manage.models import Advertisement
from adlist.models import FeedsradarModel
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt


# 信息流雷达遍历图片去水印代码，一次性执行 #
def un_watermark(request):
    image_path = '/repo/smspider/images/feedsradar_app/'  # 去水印前的图片存放路径
    # image_path = '/Users/cwd/feedsradar_app_watermark/'  # 去水印前的图片存放路径
    mark_path = './watermark/'  # 水印蒙版存放路径
    unwatermark_path = '/repo/smspider/images/feedsradar_app/un_feedsradar_app_watermark/'  # 去水印后的图片存放路径
    # unwatermark_path = '/Users/cwd/un_feedsradar_app_watermark/'  # 去水印后的图片存放路径

    images = os.listdir(image_path)  # 获取指定路径下的所有水印图片名
    marks = os.listdir(mark_path)  # 获取所有蒙版图片名
    mark_sizes = [i[:-4] for i in marks]  # 蒙版尺寸列表
    fail_lis = []

    for i in range(len(images)):
        try:
            image_name = images[i]
            if str(image_name).find('.DS_Store') == -1:
                print(image_name)
                img = Image.open(image_path + image_name)
                size = img.size
                width = size[0]  # 图片宽度
                height = size[1]  # 图片高度
                mark_name = str(width) + '_' + str(height) + '.jpg'  # 水印蒙版名

                if str(width) + '_' + str(height) in mark_sizes:  # 判断该尺寸的图片是否有对应蒙版存在，如果不存在则跳过
                    print(i + 1, 'of', len(images))
                    target = cv2.imread(image_path + image_name)  # 默认的彩色图(IMREAD_COLOR)方式读入原始图像
                    mark = cv2.imread(mark_path + mark_name, cv2.IMREAD_GRAYSCALE)  # 灰度图(IMREAD_GRAYSCALE)方式读入水印蒙版图像

                    # 参数：目标修复图像; 蒙版图(定位修复区域)
                    result = cv2.inpaint(target, mark, 5, cv2.INPAINT_TELEA)
                    cv2.imwrite(unwatermark_path + image_name, result)  # 保存去除水印后的图片
                    FeedsradarModel.objects.filter(local_img=image_name).update(un_watermark=image_name)
                else:
                    fail_lis.append(image_name)
        except Exception as e:
            print(e)
    print(fail_lis)
    print('work done')

    return JsonResponse({'msg': 'work done'})


from extra_apps.IMAGE_QUERY.predict import predict
import  datetime
@csrf_exempt
def test_tag(request):
    # image_path = 'C:/Users/Administrator/Desktop/test.jpg'
    # la = predict(image_path)
    import logging
    logging.info("test is started" + str(datetime.datetime.now()))
    advertisements = Advertisement.objects.exclude(local_img='暂无').exclude(local_img='').filter(Q(model_from='radar_app'))
    for advertisement in advertisements:
        image_path = '/repo/smspider/images/'+advertisement.model_from+'/'+advertisement.local_img
        try:
            la = predict(image_path)
            for i in range(10):
                # 用format封装image_tag_1~10，并赋值，省去for循环#
                s = '{}{}'.format('image_tag_', i)
                setattr(advertisement, s, la[i])
            advertisement.save()
        except Exception as e:
            print(e)
    # import time
    # time.sleep(3)
    print("test is end")
    return JsonResponse({'msg': la})


from django.db.models import Q


# 特征码过滤 #
def tag_filter(request):
    id = int(request.GET.get('id'))
    ad = Advertisement.objects.filter(id=id)
    image_tag_list = []
    tag_list = [ad[0].image_tag_1, ad[0].image_tag_2, ad[0].image_tag_3, ad[0].image_tag_4, ad[0].image_tag_5,
                ad[0].image_tag_6, ad[0].image_tag_7, ad[0].image_tag_8, ad[0].image_tag_9, ad[0].image_tag_10]
    image_tag_list = image_tag_list + tag_list
    ad_dict = []
    remainder = 10
    for tag in image_tag_list:
        if len(ad_dict) < 10:
            advertisements = Advertisement.objects.filter(model_from='souhu_app').filter(image_tag_1=tag).exclude(image_tag_1='暂无')[0:remainder]
            ad_dict = ad_dict + [model_to_dict(item) for item in advertisements]
            if len(ad_dict)<10:
                remainder = 10-len(ad_dict)
        else:
            break
    return JsonResponse({'json_data': ad_dict})

